using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;

namespace WinForm_Mes.CheckManagement

{
    public partial class QuotationShowForm : DevExpress.XtraEditors.XtraForm
    {
        #region 私有字段
        private readonly int _pageSize = 10;
        private int _pageIndex = 1;
        private int _total = 0;
        private readonly string _baseUrl = "http://localhost:5295/api/Quotaion/";
        private readonly HttpClient _httpClient;
        #endregion

        #region 构造函数
        public QuotationShowForm()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
            InitializeComponent();
            InitializeControls();
            BindEvents();
            LoadInitialData();
        }
        #endregion

        #region 初始化和事件绑定
        private void InitializeControls()
        {
            Text = "客户报价单管理";
            SetupGridColumns();
            SetupGridViewOptions();
            ApplyGridStyles();
        }

        private void SetupGridViewOptions()
        {
            // 设置网格视图的显示选项
            gridView1.OptionsView.ShowAutoFilterRow = false; // 不显示过滤行，避免第一行空行问题
            gridView1.OptionsView.ColumnAutoWidth = false; // 禁用自动列宽
            gridView1.OptionsView.ShowGroupPanel = false; // 隐藏分组面板
            gridView1.OptionsCustomization.AllowColumnMoving = true; // 允许列移动
            gridView1.OptionsCustomization.AllowColumnResizing = true; // 允许列宽调整
            gridView1.OptionsView.RowAutoHeight = true; // 自动行高
            gridView1.OptionsView.ShowIndicator = true; // 显示行号
            
            // 优化选中行的显示
            gridView1.FocusRectStyle = DrawFocusRectStyle.RowFocus;
            gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;

            // 设置行高
            gridView1.RowHeight = 30;
            
            // 优化表格布局
            gridControl1.Dock = DockStyle.Fill;
            gridView1.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True;
        }

        private void ApplyGridStyles()
        {
            // 美化表格外观
            // 设置表头样式
            gridView1.Appearance.HeaderPanel.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            gridView1.Appearance.HeaderPanel.BackColor = Color.FromArgb(78, 116, 171);
            gridView1.Appearance.HeaderPanel.ForeColor = Color.White;
            gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = HorzAlignment.Center;

            // 设置行样式
            gridView1.Appearance.Row.Font = new Font("微软雅黑", 9F);
            gridView1.Appearance.Row.TextOptions.HAlignment = HorzAlignment.Center;

            // 设置奇偶行颜色
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(240, 244, 250);
            gridView1.Appearance.OddRow.BackColor = Color.White;

            // 设置选中行样式
            gridView1.Appearance.FocusedRow.BackColor = Color.FromArgb(183, 211, 255);
            gridView1.Appearance.FocusedRow.ForeColor = Color.Black;

            // 美化按钮样式
            ApplyButtonStyles();
        }

        private void ApplyButtonStyles()
        {
            // 统一按钮样式
            foreach (Control control in panelControl1.Controls)
            {
                if (control is SimpleButton button)
                {
                    button.Appearance.BackColor = Color.FromArgb(78, 116, 171);
                    button.Appearance.ForeColor = Color.White;
                    button.Appearance.Font = new Font("微软雅黑", 9F);
                    button.Appearance.Options.UseBackColor = true;
                    button.Appearance.Options.UseForeColor = true;
                    button.Appearance.Options.UseFont = true;
                }
            }

            // 调整面板样式
            panelControl1.Appearance.BackColor = Color.FromArgb(240, 244, 250);
            panelControl2.Appearance.BackColor = Color.White;
            
            // 美化分页控件
            foreach (Control control in panelControl3.Controls)
            {
                if (control is SimpleButton button)
                {
                    button.Appearance.BackColor = Color.FromArgb(78, 116, 171);
                    button.Appearance.ForeColor = Color.White;
                    button.Appearance.Font = new Font("微软雅黑", 9F);
                    button.Appearance.Options.UseBackColor = true;
                    button.Appearance.Options.UseForeColor = true;
                    button.Appearance.Options.UseFont = true;
                }
                else if (control is LabelControl label)
                {
                    label.Appearance.Font = new Font("微软雅黑", 9F);
                    label.Appearance.ForeColor = Color.FromArgb(60, 60, 60);
                }
            }
        }

        private void BindEvents()
        {
            this.gridControl1.Load += GridControl1_Load;
            this.btnSearch.Click += async (s, e) => await RefreshData();
            this.btnAdd.Click += AddQuotation;
            this.btnDelete.Click += DeleteQuotation;
            this.btnExport.Click += ExportData;
            this.gridView1.DoubleClick += GridView1_DoubleClick;
            this.Load += QuotationShowForm_Load;
            this.Resize += QuotationShowForm_Resize;
            
            // 分页按钮事件
            this.btnFirst.Click += async (s, e) => await GoToPage(1);
            this.btnPrev.Click += async (s, e) => await GoToPage(_pageIndex - 1);
            this.btnNext.Click += async (s, e) => await GoToPage(_pageIndex + 1);
            this.btnLast.Click += async (s, e) => await GoToPage(CalculateLastPage());
            this.btnGo.Click += async (s, e) => await GoToPage(GetUserInputPage());
        }

        private int CalculateLastPage()
        {
            int lastPage = (_total + _pageSize - 1) / _pageSize;
            return Math.Max(1, lastPage);
        }

        private int GetUserInputPage()
        {
            if (int.TryParse(txtPageNum.Text, out int pageNum) && pageNum > 0)
            {
                return pageNum;
            }
            return _pageIndex;
        }

        private async Task GoToPage(int pageIndex)
        {
            if (pageIndex < 1 || pageIndex > CalculateLastPage()) return;
            
            _pageIndex = pageIndex;
            UpdatePaginationInfo();
            await LoadGridDataAsync();
        }

        private void UpdatePaginationInfo()
        {
            int lastPage = CalculateLastPage();
            lblPageInfo.Text = $"第 {_pageIndex} 页 / 共 {lastPage} 页  总记录数: {_total}";
            
            // 更新按钮状态
            btnFirst.Enabled = _pageIndex > 1;
            btnPrev.Enabled = _pageIndex > 1;
            btnNext.Enabled = _pageIndex < lastPage;
            btnLast.Enabled = _pageIndex < lastPage;
        }

        private void QuotationShowForm_Load(object sender, EventArgs e)
        {
            AdjustColumnWidths();
        }

        private void QuotationShowForm_Resize(object sender, EventArgs e)
        {
            AdjustColumnWidths();
        }

        private void AdjustColumnWidths()
        {
            if (gridView1 == null || gridView1.Columns.Count == 0) return;

            // 获取GridControl的可用宽度
            int totalWidth = gridControl1.Width - 30; // 减去滚动条和边框宽度
            
            // 设置各列的相对宽度比例
            var widthRatios = new Dictionary<string, double>
            {
                { "customerCode", 0.15 },
                { "customerName", 0.20 },
                { "type", 0.15 },
                { "unit", 0.10 },
                { "product", 0.15 },
                { "productNotes", 0.25 }
            };

            // 应用宽度比例
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.Columns)
            {
                if (widthRatios.ContainsKey(column.FieldName))
                {
                    column.Width = (int)(totalWidth * widthRatios[column.FieldName]);
                }
            }
        }

        private void LoadInitialData()
        {
            _ = LoadGridDataAsync();
        }
        #endregion

        #region Grid设置
        private void SetupGridColumns()
        {
            // 确保GridView已初始化
            if (gridView1 == null || gridView1.Columns == null || gridView1.Columns.Count == 0) return;

            // 设置所有列为只读
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in this.gridView1.Columns)
            {
                col.OptionsColumn.AllowEdit = false;
                col.OptionsColumn.ReadOnly = true;
                col.MinWidth = 100; // 设置最小列宽
            }

            // 检查列对象是否存在，然后设置字段名
            if (customerCode != null) customerCode.FieldName = "customerCode";
            if (customerName != null) customerName.FieldName = "customerName";
            if (type != null) type.FieldName = "type";
            if (unit != null) unit.FieldName = "unit";
            if (product != null) product.FieldName = "product";
            if (productNotes != null) productNotes.FieldName = "productNotes";

            // 设置列宽（会被自动调整覆盖）
            if (customerCode != null) customerCode.Width = 100;
            if (customerName != null) customerName.Width = 150;
            if (type != null) type.Width = 100;
            if (unit != null) unit.Width = 80;
            if (product != null) product.Width = 120;
            if (productNotes != null) productNotes.Width = 200;
        }
        #endregion

        #region 事件处理
        private void GridControl1_Load(object sender, EventArgs e)
        {
            _ = LoadGridDataAsync();
        }

        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            var focusedRow = gridView1.GetFocusedRow() as QuotationDto;
            if (focusedRow != null)
            {
                // 打开报价单编辑窗体 (可以创建一个类似AddUserForm的表单)
                MessageBox.Show($"编辑报价单: {focusedRow.customerName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // TODO: 添加编辑报价单的窗体
            }
        }

        private void AddQuotation(object sender, EventArgs e)
        {
            try
            {
                // 打开添加报价单窗体 (可以创建一个类似AddUserForm的表单)
                MessageBox.Show("添加报价单功能待实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // TODO: 添加新增报价单的窗体
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加报价单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void DeleteQuotation(object sender, EventArgs e)
        {
            try
            {
                var focusedRow = gridView1.GetFocusedRow() as QuotationDto;
                if (focusedRow == null)
                {
                    MessageBox.Show("请选择要删除的报价单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show($"确定要删除客户 {focusedRow.customerName} 的报价单吗？", "确认", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }

                var url = $"{_baseUrl}DeleteQuotation?customerCode={focusedRow.customerCode}";
                var response = await _httpClient.DeleteAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await RefreshData();
                }
                else
                {
                    MessageBox.Show("删除失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除报价单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExportData(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "Excel文件|*.xlsx",
                    Title = "导出Excel",
                    FileName = $"客户报价单_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    gridControl1.ExportToXlsx(saveFileDialog.FileName);
                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 数据加载
        private async Task RefreshData()
        {
            _pageIndex = 1;
            await LoadGridDataAsync();
        }

        private async Task LoadGridDataAsync()
        {
            try 
            {
                gridControl1.UseWaitCursor = true;
                
                var customerCode = txtCustomerCode.Text.Trim();
                var customerName = txtCustomerName.Text.Trim();

                var url = $"{_baseUrl}GetAllQuotation?PageIndex={_pageIndex}&PageSize={_pageSize}";
                if (!string.IsNullOrEmpty(customerCode))
                {
                    url += $"&CustomerCode={customerCode}";
                }
                if (!string.IsNullOrEmpty(customerName))
                {
                    url += $"&CustomerName={customerName}";
                }

                Console.WriteLine($"请求URL: {url}");

                try
                {
                    var response = await _httpClient.GetFromJsonAsync<PageResult<QuotationDto>>(url);
                    
                    if (response?.Items != null)
                    {
                        UpdateGridData(response);
                    }
                    else
                    {
                        MessageBox.Show("未获取到数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"API调用失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                gridControl1.UseWaitCursor = false;
            }
        }

        private void UpdateGridData(PageResult<QuotationDto> response)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateGridDataInternal(response)));
            }
            else
            {
                UpdateGridDataInternal(response);
            }
        }

        private void UpdateGridDataInternal(PageResult<QuotationDto> response)
        {
            gridControl1.DataSource = null;
            gridControl1.DataSource = response.Items;
            
            // 调整列宽和显示
            AdjustColumnWidths();
            
            _total = response.Total;
            UpdatePaginationInfo();
        }
        #endregion

        #region 数据模型
        public class PageResult<T>
        {
            public int Total { get; set; }
            public int PageIndex { get; set; }
            public int PageSize { get; set; }
            public List<T> Items { get; set; }
            public int Code { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

        public class QuotationDto
        {
            public string customerCode { get; set; } = string.Empty;
            public string customerName { get; set; } = string.Empty;
            public string type { get; set; } = string.Empty;
            public string unit { get; set; } = string.Empty;
            public string product { get; set; } = string.Empty;
            public string productNotes { get; set; } = string.Empty;
        }
        #endregion

        private void QuotationShowForm_Load_1(object sender, EventArgs e)
        {

        }
    }
} 